#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------
# -- EML 文件工具类
# --
# ****************************
# Author: lmay.Zhou
# Blog: www.lmaye.com
# Date: 2021/3/4 15:22
# Email lmay@lmaye.com
# ----------------------------------------------------------
import email


def read_eml(eml_file, content_type="text/html", annex_save=False, annex_path=None):
    """
    读取EML文件信息

    :param eml_file:        EML文件
    :param content_type:    内容类型
    :param annex_save:      附件保存
    :param annex_path:      附件路径
    :return: {}
    """
    eml = open(eml_file, "r")
    email_content = email.message_from_file(eml)
    subject = email_content.get("subject")
    # 解码
    sub_header = email.header.Header(subject)
    sub_decode = email.header.decode_header(sub_header)
    # 信息解析
    subject = str(sub_decode[0][0], encoding="utf8")
    from_ = email.utils.parseaddr(email_content.get("from"))[1]
    to_ = email.utils.parseaddr(email_content.get("to"))[1]
    content = ""
    # 遍历信件中的mime数据块
    for par in email_content.walk():
        # 是否是Multipart
        if not par.is_multipart():
            # 是否是附件
            name = par.get_param("name")
            if name:
                # 附件处理
                pass
            else:
                # 文本内容
                if content_type == par.get_content_type():
                    content = str(par.get_payload(decode=True), encoding="utf8")
    eml.close()
    # return {"subject": subject, "from": from_, "to": to_, "content": content}
    return [subject, from_, to_, content]
